package eg.edu.eelu.fyp2013.jdetector.core.filters.impl;

import java.awt.Color;
import java.util.Arrays;

public class MedianFilter extends AbstractWindowFilter {

	public MedianFilter(int filterWidth, int filterHeight) {
		super(filterWidth, filterHeight);
	}

	@Override
	public int getFilteredPixel(int[] window) {
		int divisor = (window.length / 2);//XXX This is a calculation mistake here < +1 was removed
		Arrays.sort(window);
		return window[divisor];
	}

	@Override 
	public int getFilteredPixel(int[][] window) {

		int [] sortedWindow = new int [window.length * window[0].length]; //create 1 dimensional array of length = (raws * columns) of the 2 dim. input array   
		int i =0;
		for (int x = 0 ; x < window.length ; x++)
			for (int y= 0 ; y< window[x].length ; y++)
				sortedWindow[i++] = window[x][y];             // assign values to the new array


		Arrays.sort(sortedWindow);						//  sort the new array
		int divisor = (window.length / 2);				//get the median index
		return sortedWindow[divisor];					//return the median value
		//Ahmed

	}

	@Override 
	public Color getFilteredPixel(Color[] windowColors) {
		//TODO Any body

		// as the color is an integer

		//tried to remove the alpha value!!
		//Color [] RGBWindow = new Color [windowColors.length];
		//for (int i =0 ; i < RGBWindow.length ; i++)
		//	RGBWindow[i] =  windowColors[i].getRGB();

		Arrays.sort(windowColors);	//XXX Color is NOT an integer and you shall not work on the color altogether
		int divisor = (windowColors.length / 2);
		return windowColors[divisor];
		//Ahmed
	}



	@Override
	public Color getFilteredPixel(Color[][] windowColors) {
		//TODO Any body

		// as the color is an integer

		Color [] sortedWindow = new Color [windowColors.length * windowColors[0].length]; //create 1 dimensional array of length = (raws * columns) of the 2 dim. input array 
		int i =0;
		for (int x = 0 ; x < windowColors.length ; x++)
			for (int y= 0 ; y< windowColors[x].length ; y++)
				sortedWindow[i++] = windowColors[x][y];             // assign values to the new array

		//XXX Color is NOT an integer and you shall not work on the color altogether
		
		Arrays.sort(sortedWindow);									//  sort the new array
		int divisor = (sortedWindow.length / 2);					//get the median index
		return sortedWindow[divisor];								//return the median value
		//Ahmed
	}

}
